package com.front.managementfront.region.controller;


import com.alibaba.fastjson.JSONObject;
import com.front.managementfront.config.properties.AmapProperties;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.front.managementfront.utils.CustomPageUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.front.managementfront.region.service.IHktsRegionService;
import com.front.managementfront.region.entity.HktsRegion;

/**
 * @author yck
 * @since 2021-05-12
 */
@RestController
@RequestMapping("/front/hktsRegion")
@Api(tags = "行政区管理")
public class HktsRegionController {
    private final Logger logger = LoggerFactory.getLogger(HktsRegionController.class);

    @Autowired
    public IHktsRegionService iHktsRegionService;


    @Autowired
    private AmapProperties amapProperties;

    /**
     * 分页查询数据
     *
     * @param page       分页信息
     * @param hktsRegion 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getHktsRegionPageList")
    public Result<Object> getHontUserList(Page<HktsRegion> page, HktsRegion hktsRegion) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsRegionService.selectPage(page, hktsRegion)));
    }

    /**
     * 保存和修改公用的
     *
     * @param hktsRegion 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsRegionSave")
    public Result<Object> hktsRegionSave(HktsRegion hktsRegion) {
        iHktsRegionService.saveOrUpdate(hktsRegion);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsRegionGetById")
    public Result<Object> hktsRegionGetById(String id) {
        HktsRegion byId = iHktsRegionService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsRegionDelete")
    public Result<Object> hontUserDelete(String id) {
        iHktsRegionService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsRegionBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iHktsRegionService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    /**
     * 根据父级code进行
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsRegionsGetByParentCode")
    @ApiOperation(value = "行政区划查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentCode", value = "父级code", dataType = "integer"),
            @ApiImplicitParam(name = "regionName", value = "城市名称", dataType = "string")
    })

    public Result<List<HktsRegion>> hktsRegionGetById(HktsRegion hegion) {

        List<HktsRegion> hktsRegions = iHktsRegionService.selectListByCondition(hegion);
        return ResultUtil.data(hktsRegions);
    }

    /**
     * 数据处理
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsRegionHandler")
    public Result<Object> hktsRegionHandler() {
        HktsRegion region = new HktsRegion();
        List<HktsRegion> hktsRegions = iHktsRegionService.selectList(region);
        hktsRegions.stream().forEach(hktsRegion -> {
        /*if(hktsRegion.getRegionAlias().length()>1&&(hktsRegion.getRegionAlias().endsWith("市")||hktsRegion.getRegionAlias().endsWith("县"))){
            hktsRegion.setRegionAlias(hktsRegion.getRegionAlias().substring(0,hktsRegion.getRegionAlias().length()-1));
            iHktsRegionService.saveOrUpdate(hktsRegion);
        }*/

            if (!hktsRegion.getRegionAlias().equals("开发区") && hktsRegion.getRegionAlias().endsWith("区")) {
                hktsRegion.setRegionAlias(hktsRegion.getRegionAlias().substring(0, hktsRegion.getRegionAlias().length() - 1));
                iHktsRegionService.saveOrUpdate(hktsRegion);
            }
        });



        return ResultUtil.success("处理成功！");
    }

    /**
     * 获取父级name
     * @param regionCod
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getRegionName/{regionCod}")
    public Result<String> getRegionName(@PathVariable String regionCod) {

        String prentName = iHktsRegionService.getPrentName(regionCod);
        return ResultUtil.data(prentName);

    }
    /**
     * 获取父级code
     * @param regionCod
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getRegionCode/{regionCod}")
    public Result<List<Integer>> getRegionCode(@PathVariable String regionCod) {

        String prentName = iHktsRegionService.getPrentRegionCode(regionCod);
        String substring = prentName.substring(1);
        List<Integer> collect = Arrays.asList(substring.split(" ")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        return ResultUtil.data(collect);

    }
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsRegionGetByCode/{code}")
    public Result<HktsRegion> hktsRegionGetByCode(@PathVariable String code) {
        HktsRegion byId = iHktsRegionService.getRegionByCode(code);
        return ResultUtil.data(byId);
    }

    @GetMapping("/getregionRedisByCode")
    public String getregionRedisByCode (@RequestParam("code") int code){
        return iHktsRegionService.getRegionRedisByCode(code);
    }



    /** 功能描述:
     *测试feign 远程调用 高德地图
     * @return:
     * @Author: 杨春科
     * @Date: 2021-07-10 13:59
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getTipsData")
    public Result<Map<String,Object>> getTipsData(String content,String cityCode){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        URI uri = null;
        try {
            // 将参数放入键值对类NameValuePair中,再放入集合中
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("key", amapProperties.getAmapKey()));
            params.add(new BasicNameValuePair("keywords", content));
          //  params.add(new BasicNameValuePair("type", "170200"));
            params.add(new BasicNameValuePair("citylimit", "true"));
            params.add(new BasicNameValuePair("city", cityCode));
            // 设置uri信息,并将参数集合放入uri;
            // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
            uri = new URIBuilder().setScheme("https").setHost("restapi.amap.com")
                    .setPath("//v3/assistant/inputtips")
                    .setParameters(params).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);
        // 响应模型
        CloseableHttpResponse response = null;
        HttpEntity responseEntity=null;
        String json=null;
        Map<String ,Object> jsonObject=new HashMap<String ,Object>();
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());

            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                json=EntityUtils.toString(responseEntity);
                Gson gson=new Gson();
                jsonObject=gson.fromJson(json,Map.class);
                List<Map<String,Object>> list =(List<Map<String,Object>>)jsonObject.get("tips");
                String cityCodeSub="";
                if(cityCode.substring(2, 4).equals("00")){
                    cityCodeSub = cityCode.substring(0, 2);
                }else{
                   cityCodeSub = cityCode.substring(0, 4);
                }
                for(Iterator iter = list.iterator(); iter.hasNext();){
                    Map<String,Object> map=(Map<String,Object>)iter.next();
                    if(!map.get("adcode").toString().startsWith(cityCodeSub)){
                        iter.remove();
                    }
                }
                jsonObject.put("count",list.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.data(jsonObject);
    }


    /** 功能描述:
     *测试feign 远程调用 QQ地图
     * @return:   TOOBZ-US26W-NGCRV-OLS4P-F3Q26-IMF7D
     * @Author: 杨春科
     * @Date: 2021-07-10 13:59
     * @Description //TODO
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/getQqsData")
    public Result<Map<String,Object>> getQqsData(String content,String region){
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        URI uri = null;
        try {
            // 将参数放入键值对类NameValuePair中,再放入集合中
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("key", amapProperties.getQqkey()));
            params.add(new BasicNameValuePair("region", region));
            //  params.add(new BasicNameValuePair("type", "170200"));
            params.add(new BasicNameValuePair("keyword", content));
            params.add(new BasicNameValuePair("region_fix", "1"));
            // 设置uri信息,并将参数集合放入uri;
            // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
            uri = new URIBuilder().setScheme("https").setHost("apis.map.qq.com")
                    .setPath("/ws/place/v1/suggestion")
                    .setParameters(params).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);
        // 响应模型
        CloseableHttpResponse response = null;
        HttpEntity responseEntity=null;
        String json=null;
        Map<String ,Object> jsonObject=new HashMap<String ,Object>();
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());

            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                json=EntityUtils.toString(responseEntity);
                Gson gson=new Gson();
                jsonObject=gson.fromJson(json,Map.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.data(jsonObject);
    }
}
